Summary of PHP Common Class Encapsulation [4 Tool Classes]

  • 2021-12-12 04:05:20
  • OfStack

In this paper, an example is given to describe the class encapsulation commonly used in PHP. Share it for your reference, as follows:

These four classes are Mysql class, paging class, thumbnail class and upload class.

Class Mysql


<?php
/**
 * Mysql Class 
 */
class Mysql{
  private static $link = null;// Database connection 
  /**
   *  Private constructor 
   */
  private function __construct(){}
  /**
   *  Connect to a database 
   * @return obj  Resource object 
   */
  private static function conn(){
    if(self::$link === null){
      $cfg = require './config.php';
      self::$link = new Mysqli($cfg['host'],$cfg['user'],$cfg['pwd'],$cfg['db']);
      self::query("set names ".$cfg['charset']);// Set the character set 
    }
    return self::$link;
  }
  /**
   *  Execute 1 Article sql Statement 
   * @param str $sql  Query statement 
   * @return obj    Result set object 
   */
  public static function query($sql){
    return self::conn()->query($sql);
  }
  /**
   *  Get multiple rows of data 
   * @param str $sql  Query statement 
   * @return arr    Multiple rows of data 
   */
  public static function getAll($sql){
    $data = array();
    $res = self::query($sql);
    while($row = $res->fetch_assoc()){
      $data[] = $row;
    }
    return $data;
  }
  /**
   *  Get 1 Row data 
   * @param str $row  Query statement 
   * @return arr    Single row data 
   */
  public static function getRow($row){
    $res = self::query($sql);
    return $res->fetch_assoc();
  }
  /**
   *  Get a single result 
   * @param str $sql  Query statement 
   * @return str    Single result 
   */
  public static function getOne($sql){
    $res = self::query($sql);
    $data = $res->fetch_row();
    return $data[0];
  }
  /**
   *  Insert / Update data 
   * @param str $table  Table name 
   * @param arr $data  Insert / Updated data 
   * @param str $act  insert/update
   * @param str $where  Update condition 
   * @return bool  Insert / Is the update successful 
   */
  public static function exec($table,$data,$act='insert',$where='0'){
    // Insert operation 
    if($act == 'insert'){
      $sql = 'insert into '.$table;
      $sql .= ' ('.implode(',',array_keys($data)).')';
      $sql .= " values ('".implode("','",array_values($data))."')";
    }else if($act == 'update'){
      $sql = 'update '.$table.' set ';
      foreach ($data as $k => $v) {
        $sql .= $k.'='."'$v',";
      }
      $sql = rtrim($sql,',');
      $sql .= ' where 1 and '.$where;
    }
    return self::query($sql);
  }
  /**
   *  Get the most recent 1 Primary key value of secondary insertion 
   * @return int  Primary key 
   */
  public static function getLastId(){
    return self::conn()->insert_id;
  }
  /**
   *  Get the most recent 1 Number of rows affected by this operation 
   * @return int  Number of rows affected 
   */
  public static function getAffectedRows(){
    return self::conn()->affected_rows;
  }
  /**
   *  Close the database connection 
   * @return bool  Whether to close 
   */
  public static function close(){
    return self::conn()->close();
  }
}
?>

Paging class


<?php
/**
 *  Paging class 
 * @author webbc
 */
class Page{
  private $num;// Total number of articles 
  private $cnt;// Number of articles displayed per page 
  private $curr;// Current page number 
  private $p = 'page';// Paging parameter name 
  private $pageCnt = 5;// Total number of pages displayed by column 
  private $firstRow;// The page of each page 1 Row data 
  private $pageIndex = array();// Paging information 
  /**
   *  Constructor 
   * @param int $num  Total number of articles 
   * @param int $cnt  Number of articles displayed per page 
   */
  public function __construct($num,$cnt=10){
    $this->num = $num;
    $this->cnt = $cnt;
    $this->curr = empty($_GET[$this->p]) ? 1 : intval($_GET[$this->p]);
    $this->curr = $this->curr > 0 ? $this->curr : 1;
    $this->firstRow  = $this->cnt * ($this->curr - 1);
    $this->getPage();
  }
  /**
   *  Paging method 
   */
  private function getPage(){
    $page = ceil($this->num / $this->cnt);// Total number of pages 
    $left = max(1,$this->curr - floor($this->pageCnt/2));// Calculate the leftmost page number 
    $right = min($left + $this->pageCnt - 1 ,$page);// Calculate the rightmost page number 
    $left = max(1,$right - ($this->pageCnt - 1));// The current page number is leaning to the right, and the value of the left page needs to be recalculated 
    for($i=$left;$i<=$right;$i++){
      if($i == 1){
        $index = ' No. 1 1 Page ';
      }else if($i == $page){
        $index = ' Finally 1 Page ';
      }else{
        $index = ' No. 1 '.$i.' Page ';
      }
      $_GET['page'] = $i;
      $this->pageIndex[$index] = http_build_query($_GET);
    }
  }
  /**
   *  Returns paging information data 
   * @return [type] [description]
   */
  public function show(){
    return $this->pageIndex;
  }
}
?>

Thumbnail class


<?php
/**
 *  Thumbnail class 
 * @author webbc
 */
class Thumb{
  private $thumbWidth;// Width of thumbnail 
  private $thumbHeight;// Height of thumbnail 
  private $thumbPath;// Path to save thumbnails 
  private $sourcePath;// Path of the original image 
  private $sourceWidth;// Width of original drawing 
  private $sourceHeight;// Height of the original drawing 
  private $sourceType;// Picture type of original image 
  /**
   *  Constructor 
   * @param str $sourcePath  Absolute path of original image 
   * @param integer $thumbWidth  Width of thumbnail 
   * @param integer $thumbHeight  Height of thumbnail 
   */
  public function __construct($sourcePath,$thumbWidth=200,$thumbHeight=200){
    // Get the absolute path of the original image 
    $this->sourcePath = $sourcePath;
    // Gets the size of the thumbnail 
    $this->thumbWidth = $thumbWidth;
    $this->thumbHeight = $thumbHeight;
    $this->thumbPath = $this->getThumbPath();
    // Calculate the size of a large graph 
    list($this->sourceWidth,$this->sourceHeight,$this->sourceType) = getimagesize($this->sourcePath);
  }
  /**
   *  Determine the path to save thumbnails 
   * @return [type] [description]
   */
  private function getThumbPath(){
    $ext = $this->getExt();
    $filename = basename($this->sourcePath,'.'.$ext).'_thumb'.'.'.$ext;
    return $thumbPath = __DIR__.'/'.$filename;
  }
  /**
   *  Get the extension of the original image 
   * @return str  Extensions 
   */
  private function getExt(){
    return pathinfo($this->sourcePath,PATHINFO_EXTENSION);
  }
  /**
   *  Check whether the extension of the original image is legal and return the corresponding type 
   * @return bool/str  Type of original drawing 
   */
  public function getType(){
    $typeArr = array(
      1 => 'gif',
      2 => 'jpeg',
      3 => 'png',
      15 => 'wbmp'
    );
    if(!in_array($this->sourceType, array_keys($typeArr))){
      return false;
    }
    return $typeArr[$this->sourceType];
  }
  /**
   *  Calculate the scaling ratio of the large image according to the thumbnail size 
   * @return float  Scale ratio 
   */
  public function calculateRate(){
    return min($this->thumbWidth / $this->sourceWidth,$this->thumbHeight / $this->sourceHeight);
  }
  /**
   *  Calculate the final image size after the large image is scaled 
   * @param float $rate  Scale ratio 
   * @return arr  Scaled picture size 
   */
  public function getImageSizeByRate($rate){
    $width = $this->sourceWidth * $rate;
    $height = $this->sourceHeight * $rate;
    return array('w'=>$width,'h'=>$height);
  }
  /**
   *  Save as a file 
   * @return [type] [description]
   */
  public function saveFile($image){
    $method = "image".$this->getType();
    $method($image,$this->thumbPath);
  }
  /**
   *  Carry out painting operation 
   * @return [type] [description]
   */
  public function draw(){
    if(!($type = $this->getType())){
      echo " File type not supported ";
      return ;
    }
    // Create canvases for large and small pictures 
    $method = "imagecreatefrom".$type;
    $bigCanvas = $method($this->sourcePath);
    $smallCanvas = imagecreatetruecolor($this->thumbWidth, $this->thumbHeight);
    // Create a white brush and fill the background of the small drawing cloth 
    $white = imagecolorallocate($smallCanvas, 255, 255, 255);
    imagefill($smallCanvas, 0, 0, $white);
    // Calculate the scaling ratio of the large graph 
    $rate = $this->calculateRate();
    // Calculate the size information after scaling the large picture 
    $info = $this->getImageSizeByRate($rate);
    // Zoom 
    imagecopyresampled($smallCanvas, $bigCanvas,
      ($this->thumbWidth - $info['w']) / 2 , ($this->thumbHeight - $info['h']) / 2,
      0, 0, $info['w'], $info['h'], $this->sourceWidth, $this->sourceHeight);
    // Save as a file 
    $this->saveFile($smallCanvas);
    // Destroy canvas 
    imagedestroy($bigCanvas);
    imagedestroy($smallCanvas);
  }
}
?>

Upload class


<meta charset="utf8"/>
<?php
/**
 *  File upload class 
 * @author webbc
 */
class Upload{
  private $allowExt = array('gif','jpg','jpeg','bmp','png','swf');// Restrict the suffix name of file upload 
  private $maxSize = 1;// Limit the maximum file upload 1M
  /**
   *  Get the information of the file 
   * @param str $flag  Identity of uploaded file 
   * @return arr     Information array of uploaded files 
   */
  public function getInfo($flag){
    return $_FILES[$flag];
  }
  /**
   *  Get the extension of the file 
   * @param str $filename  Filename 
   * @return str  File extension 
   */
  public function getExt($filename){
    return pathinfo($filename,PATHINFO_EXTENSION);
  }
  /**
   *  Check if the file extension is legal 
   * @param str $filename  Filename 
   * @return bool  Is the file extension legal 
   */
  private function checkExt($filename){
    $ext = $this->getExt($filename);
    return in_array($ext,$this->allowExt);
  }
  /**
   *  Detect whether the file size exceeds the limit 
   * @param int size  File size 
   * @return bool  Does the file size exceed the limit 
   */
  public function checkSize($size){
    return $size < $this->maxSize * 1024 * 1024;
  }
  /**
   *  Random file name 
   * @param int $len  Length of random file name 
   * @return str  Random string 
   */
  public function randName($len=6){
    return substr(str_shuffle('abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ234565789'),0,$len);
  }
  /**
   *  Create the path to upload the file 
   * @return str  Path to upload files 
   */
  public function createDir(){
    $dir = './upload/'.date('Y/m/d',time());
    if(is_dir($dir) || mkdir($dir,0777,true)){
      return $dir;
    }
  }
  /**
   *  File upload 
   * @param str $flag  File upload identification 
   * @return arr  File upload information 
   */
  public function uploadFile($flag){
    if($_FILES[$flag]['name'] === '' || $_FILES[$flag]['error'] !== 0){
      echo " No file uploaded ";
      return;
    }
    $info = $this->getInfo($flag);
    if(!$this->checkExt($info['name'])){
      echo " Unsupported file type ";
      return;
    }
    if(!$this->checkSize($info['size'])){
      echo " File size exceeds limit ";
      return;
    }
    $filename = $this->randName().'.'.$this->getExt($info['name']);
    $dir = $this->createDir();
    if(!move_uploaded_file($info['tmp_name'], $dir.'/'.$filename)){
      echo " File upload failed ";
    }else{
      return array('filename'=>$filename,'dir'=>$dir);
    }
  }
}
?>

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php+mysql Database Operation", "Summary of php+mysqli Database Programming Skills", "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Summary of PHP Network Programming Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: